package akayblog;

import akayblog.EntryComponent.MODE;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;

@SuppressWarnings("serial")
public class SubWindow extends Window {

	private VerticalLayout mainLayout;

	private VerticalLayout parentLayout;

	private EntryComponent entryComponent;

	private BlogService blogService;
	
	private MyTree tree;
	
	private MainWindow mainWindow;

	public SubWindow(VerticalLayout parentLayout,MainWindow mainWindow) {
		this.parentLayout = parentLayout;
		this.mainWindow=mainWindow;
		blogService = new BlogService();
		buildMainLayout();
		
	}

	private void buildMainLayout() {
		this.setCaption("Yeni kayıt");
		mainLayout = new VerticalLayout();
		mainLayout.setSpacing(true);
		mainLayout.setMargin(true);
		Entry entry = new Entry();
		entry.setTitle("");
		entry.setText("");
		entryComponent = new EntryComponent(entry);
		entryComponent.setCurrentMode(MODE.EDIT);
		mainLayout.addComponent(entryComponent);
		setContent(mainLayout);
		setModal(true);
		setWidth("60%");
		setHeight("75%");

		entryComponent.getSave().addListener(new ClickListener() {

			@Override
			public void buttonClick(ClickEvent event) {
				Entry nEntry = entryComponent.getEntry();
				int id = blogService.addEntry(nEntry);
				nEntry.setId(id);
				final EntryComponent newEntryComponent = new EntryComponent(
						nEntry);
				

				newEntryComponent.getSave().addListener(new ClickListener() {

					/**
					 * 
					 */
					private static final long serialVersionUID = 1L;

					@Override
					public void buttonClick(ClickEvent event) {
						blogService.updateEntry(newEntryComponent.getEntry());

						newEntryComponent.setCurrentMode(MODE.READ);

					}
				});
				
				mainWindow.refresh();
				parentLayout.addComponent(newEntryComponent, 0);
				parentLayout.setComponentAlignment((newEntryComponent),
						Alignment.TOP_CENTER);

				SubWindow.this.getParent().removeWindow(SubWindow.this);

			}
		});

	}

}
